package com.imdroid.carac.activities;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.imdroid.carac.R;

/**
 * The activity of anti-theft
 * 
 */
public class SecurityStartupActivity extends BaseActivity {
	/**
	 * The TAG of this activity
	 */
	private final static String TAG = "SecurityStartupActivity";
	/**
	 * The button of start
	 */
	private Button btnStart;
	/**
	 * The battery change receiver
	 */
	private BroadcastReceiver batteryChangeReceiver = new BatteryChangeReceiver();
	/**
	 * the thread of timer
	 */
	private TimeRunner timeRunner = null;
	/**
	 * The text of start
	 */
	private String startText;
	/**
	 * The time finish
	 */
	private long timeFinish = 0;
	/**
	 * If need to exit automatically if the power is plug again.
	 */
	private boolean autoBack = false;
	private WakeLock wl;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 初始化界面控件
		setContentView(R.layout.security_start);
		btnStart = (Button) this.findViewById(R.id.scurity_start_start);
		//allowBack = false;
		startText = btnStart.getText() + "";

		// 启动线程
		// timeRunner = new TimeRunner(5 * 60 * 1000, 1 * 1000);
		timeRunner = new TimeRunner(120 * 1000, 1 * 1000);
		timeRunner.start();

		// 判断是否需要自动后退（如果有插上电的情况下）
		// if (this.getIntent().getExtras() != null) {
		// autoBack = this.getIntent().getExtras().getBoolean("autoBack");
		// }
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.imdroid.carac.activities.BaseActivity#onResume()
	 */
	protected void onResume() {
		super.onResume();
		autoBack = false;

		this.registerReceiver(batteryChangeReceiver, new IntentFilter(
				Intent.ACTION_BATTERY_CHANGED));
		wl = ((PowerManager) getSystemService(Activity.POWER_SERVICE))
				.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP
						| PowerManager.FULL_WAKE_LOCK, "");
		wl.acquire();
		final Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			public void run() {
				this.cancel();
				timer.cancel();
			}
		}, 10000);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onPause()
	 */
	protected void onPause() {
		if (wl != null)
			wl.release();
		this.unregisterReceiver(batteryChangeReceiver);
		super.onPause();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onDestroy()
	 */
	protected void onDestroy() {
		if (timeRunner != null)
			timeRunner.cancel();
		super.onDestroy();
	}

	/**
	 * Back to the main screen
	 * 
	 * @param view
	 *            the of button
	 */
	public void start(View view) {
		Intent intent = new Intent(this, SecurityHomeActivity.class);
		intent.putExtra("timeFinished", timeFinish);
		startActivity(intent);
		this.finish();
	}

	/**
	 * Back to the main screen
	 * 
	 * @param view
	 *            the of button
	 */
	public void exit(View view) {
		this.finish();
	}

	/**
	 * The action of back
	 * 
	 * @param view
	 *            the button of back
	 */
	public void back(View view) {
		this.finish();
	}

	/**
	 * The time runner
	 */
	private class TimeRunner extends CountDownTimer {

		/**
		 * The constructor of time runner
		 * 
		 * @param millisInFuture
		 * @param countDownInterval
		 */
		public TimeRunner(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.CountDownTimer#onFinish()
		 */
		public void onFinish() {
			SecurityStartupActivity.this.start(btnStart);
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.CountDownTimer#onTick(long)
		 */
		@SuppressLint("SimpleDateFormat")
		public void onTick(long millisUntilFinished) {
			timeFinish = millisUntilFinished;
			SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
			String text = startText + "("
					+ sdf.format(new Date(millisUntilFinished)) + ")";
			btnStart.setText(text);

		}
	}

	/**
	 * The class of battery change recevier
	 * 
	 */
	private class BatteryChangeReceiver extends BroadcastReceiver {
		private static final int BATTERY_PLUGGED_UNPLUG = 0;

		/*
		 * (non-Javadoc)
		 * 
		 * @see
		 * android.content.BroadcastReceiver#onReceive(android.content.Context,
		 * android.content.Intent)
		 */
		public void onReceive(Context context, Intent intent) {
			int plugged = intent.getIntExtra("plugged", BATTERY_PLUGGED_UNPLUG);

			// 重新街电时
			if (plugged != BATTERY_PLUGGED_UNPLUG && autoBack) {
				Log.d(TAG, "The power is plug");
				SecurityStartupActivity.this.finish();
			}
			autoBack = true;
		}
	}
}
